<template>
  <div class="app-container">


    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable placeholder="宝贝名称" style="width: 200px;" class="filter-item"
                @keyup.enter.native="getList()"/>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" circle @click="getList"></el-button>
      <br>
      <el-button-group>
        <el-button class="filter-item" size="mini" type="danger" icon="el-icon-delete" @click="handleDelete">删除
        </el-button>
        <el-button class="filter-item" size="mini" type="primary" icon="el-icon-delete" @click="add">添加</el-button>

      </el-button-group>
    </div>
    <el-table
      ref="singleTable"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>

      <el-table-column label="推荐id" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.recommendId }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商品ID" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="推荐排序" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <el-input v-model="scope.row.recommendSort" placeholder="请输入排序号"
                    @blur="handleChange(scope.row.recommendId,scope.row.recommendSort)"></el-input>
        </template>

      </el-table-column>

      <el-table-column label="店铺" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.shopName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品类目" width="100px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.cateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="宝贝标题" min-width="200px" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.title" placement="top">
            <span class="line1">
              <span v-if="scope.row.type != 1"
                    :style="scope.row.type == 2 ? 'color:red;' : 'color:green;' ">[{{
                  scope.row.type | typeFilter
                }}]</span>
              {{ scope.row.title }}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="宝贝主图" width="80px" align="center">
        <template slot-scope="scope">
          <el-image
            style="height: 30px"
            :src="scope.row.mainImg+'?'+$globalImageProcessingSuffix"
            :preview-src-list="[scope.row.mainImg]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="宝贝相册" width="150px">
        <template slot-scope="scope">
          <div class="line1">
            <el-image
              v-for="(item,index) in scope.row.goodsImg.split('|')"
              :key="index"
              style="height: 30px;margin-left: 5px;"
              :src="item+'?'+$globalImageProcessingSuffix"
              :preview-src-list="scope.row.goodsImg.split('|')">
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="价格" width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.price | moneyFormat }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点击" width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.pointNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="素材下载量-视频" width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.trendsDownloadNumVideo }}</span>
        </template>
      </el-table-column>
      <el-table-column label="素材下载量-图片" width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.trendsDownloadNumImg }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收藏" width="70px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.collectionNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="推荐时间" width="150px" align="center" prop="addTime">
        <template slot-scope="scope">
          <span>{{ scope.row.recommendTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center" prop="addTime">
        <template slot-scope="scope">
          <span>{{ scope.row.addTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status == 1 ? 'success' : 'danger' ">{{ scope.row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template>
          <i class="el-icon-rank handle move" style="  cursor: pointer; "></i>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>

    <!--商品属性框-->
    <el-dialog title="商品参数" :visible.sync="dialogFormVisible">

      <el-table :data="goodsQualityList" border fit highlight-current-row style="width: 100%;">
        <el-table-column label="排序" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.sort }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参数名称" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参数值" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.value }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <el-dialog
      title="推荐商品添加"
      :visible.sync="dialogVisibleGoodsRecommend"
      width="70%">
      <div class="filter-container">
        <el-input v-model="listQueryAll.title" clearable placeholder="宝贝名称" style="width: 200px;"
                  class="filter-item" @keyup.enter.native="getAllList()"/>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" circle
                   @click="getAllList"></el-button>
        <br>
        <el-button-group>
          <el-button class="filter-item" type="primary" size="mini" icon="el-icon-upload2" @click="addChooseGoods">
            添加选中项
          </el-button>
        </el-button-group>
        <el-radio-group v-model="radio" @input="changeValue">
          <el-radio :label="1" style="margin-left: 10px">直接添加</el-radio>
          <el-radio :label="2" style="margin-left: 10px">使用推荐币购买</el-radio>
        </el-radio-group>


      </div>
      <el-table
        :key="tableKey"
        :data="allList"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >

        <!--        <el-table-column type="selection" width="55" align="center" v-if="radio===1"></el-table-column>-->

        <!--        <el-table-column width="50" align="center" v-else>-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-radio :label="scope.row.id" v-model="selectGoodId">{{ '' }}</el-radio>-->
        <!--          </template>-->
        <!--        </el-table-column>-->


        <el-table-column v-if="isSingle" align="center" width="55" label="选择">
          <!--          <template slot="header"> <span>选择</span> </template>-->
          <template scope="scope">
            <el-radio :label="scope.$index" v-model="selectGoodId"
                      @change.native="getCurrentRow(scope.row)">{{ '' }}
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="selection" width="55" v-else/>


        <el-table-column label="ID" prop="id" align="center" width="65">
          <template slot-scope="scope">
            <span>{{ scope.row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="店铺" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.shopName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品类目" width="100px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.cateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="宝贝标题" min-width="200px" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.title" placement="top">
            <span class="line1">
              <span v-if="scope.row.type != 1"
                    :style="scope.row.type == 2 ? 'color:red;' : 'color:green;' ">[{{
                  scope.row.type | typeFilter
                }}]</span>
              {{ scope.row.title }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="宝贝主图" width="80px" align="center">
          <template slot-scope="scope">
            <el-image
              style="height: 30px"
              :src="scope.row.mainImg+'?vframe/jpg/offset/0/?imageView2/0/interlace/1/q/29'"
              :preview-src-list="[scope.row.mainImg]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="宝贝相册" width="150px">
          <template slot-scope="scope">
            <div class="line1">
              <el-image
                v-for="(item,index) in scope.row.goodsImg.split('|')"
                :key="index"
                style="height: 30px;margin-left: 5px;"
                :src="item+'?vframe/jpg/offset/0/?imageView2/0/interlace/1/q/29'"
                :preview-src-list="scope.row.goodsImg.split('|')">
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="70px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.price | moneyFormat }}</span>
          </template>
        </el-table-column>
        <el-table-column label="点击" width="70px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.pointNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="素材下载量-视频" width="70px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.trendsDownloadNumVideo }}</span>
          </template>
        </el-table-column>
        <el-table-column label="素材下载量-图片" width="70px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.trendsDownloadNumImg }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收藏" width="70px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.collectionNum }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="150px" align="center" prop="addTime">
          <template slot-scope="scope">
            <span>{{ scope.row.addTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100px" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger' ">{{ scope.row.status | statusFilter }}</el-tag>
          </template>
        </el-table-column>

      </el-table>

      <pagination v-show="totalAll>0" :total="totalAll" :page.sync="listQueryAll.page"
                  :limit.sync="listQueryAll.pageSize" @pagination="getAllList"/>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisibleGoodsRecommend = false">取 消</el-button>

    </span>
    </el-dialog>


    <el-dialog
      title="使用推荐币"
      :visible.sync="dialogVisibleGoodsRecommendByVirtualCurrency"
      width="20%">
      <div>
        <span>当前推荐商品：{{ currentGoodsTitle }}</span>
      </div>
      <div style="margin-top: 10px;">
        <span>当前拥有推荐币：{{ currentVirtualCurrency }}</span>
      </div>

      <el-select v-model="selectBuyDayType" placeholder="请选择" style="margin-top: 10px;">
        <el-option
          v-for="item in selectBuyDayTypeList"
          :data-custom-attribute="item.id"
          :disabled="item.disabled"
          :key="item.value"
          :label="item.label"
          :value="item.id">
          <span style="float: left">{{ item.label }}</span>
          <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
        </el-option>
      </el-select>
      <div style="text-align:center;margin-top: 10px;">
        <el-button type="danger" @click="dialogVisibleGoodsRecommendByVirtualCurrency=false">取消</el-button>
        <el-button type="primary" @click="confirmRecommendByTjb">确定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  batchAddGoodsRecommendList,
  getGoodsRecommendList,
  getGoodsList,
  batchDeleteGoodsRecommend,
  getGoodsQualityList,
  addGoodsQuality,
  deleteGoodsQuality
} from '@/api/goods'
import waves from '@/directive/waves' // Waves directive
import {parseTime, renderTime} from '@/utils'
import Pagination from '@/components/Pagination'
import Sortable from "sortablejs";
import {batchAddGoodsRecommendListByVirtualCurrency, updateSort} from "../../../api/goods";
import {checkShopLevel} from "../../../api/shopLevel";
import {getInfoById} from "../../../api/shop";
import {routeFilterByPath} from "../../../store/modules/permission_back";


const typeOptions = [
  {key: 1, text: '普通'},
  {key: 2, text: '秒杀'},
  {key: 3, text: '拼团'},
]

// arr to obj ,such as { CN : "China", US : "USA" }
const typeKeyValue = typeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})

const statusOptions = [
  {key: 1, text: '上架'},
  {key: 2, text: '仓库'},
]

// arr to obj ,such as { CN : "China", US : "USA" }
const statusKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.text
  return acc
}, {})

export default {
  name: 'goodsList',
  components: {Pagination},
  directives: {waves},
  filters: {
    typeFilter(status) {
      return typeKeyValue[status]
    },
    statusFilter(type) {
      return statusKeyValue[type]
    },
  },
  data() {
    return {
      currentGoodsTitle: "",
      currentChooseGoods: null,
      isSingle: false,
      selectGoodId: null,
      selectBuyDayTypeList: [
        {
          disabled: true,
          id: 1,
          num: 24,
          value: '24个币',
          label: '一天'
        }, {
          disabled: true,
          id: 2,
          num: 70,
          value: '70个币',
          label: '三天'
        }, {
          disabled: true,
          id: 3,
          num: 149,
          value: '149个币',
          label: '七天'
        }, {
          disabled: true,
          id: 4,
          num: 326,
          value: '326个币',
          label: '十五天'
        }, {
          disabled: true,
          id: 5,
          num: 600,
          value: '600个币',
          label: '三十天'
        }],
      selectBuyDayType: "",
      currentVirtualCurrency: 0,
      radio: 1,
      dialogVisibleGoodsRecommendByVirtualCurrency: false,
      allList: [],
      dialogVisibleGoodsRecommend: false,
      props: {label: 'name', value: 'id', children: 'children', checkStrictly: true, multiple: true},
      tableKey: 0,
      list: null,
      total: 0,
      totalAll: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
      },
      listQueryAll: {
        page: 1,
        pageSize: 20,
      },
      couponConfig: {},
      dialogFormVisible: false,
      dialogType: '',
      multipleSelection: [],
      typeOptions,
      activeName: 'second',
      goodsOptions: [],
      shopCateOptions: [],
      goodsQuality: {},
      goodsQualityList: [],
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.dragSort()
  },
  methods: {
    getCurrentRow(item) {
      this.currentChooseGoods = item
      this.currentGoodsTitle = item.title
    },
    changeValue(item) {
      this.radio = item
      if (item === 1) {
        this.isSingle = false
      } else {
        this.isSingle = true
      }
    },
    handleChange(recommendId, recommendSort) {
      //修改这一行
      this.$confirm('您确定要修改记录的排序吗?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.updateSortById(recommendId, recommendSort)
      })

    },
    updateSortById(recommendId, recommendSort) {
      let formData = {
        id: recommendId,
        sort: recommendSort
      }
      updateSort(formData).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '修改排序成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    dragSort() {
      const el = this.$refs.singleTable.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      this.sortable = Sortable.create(el, {
        handle: ".move",
        onEnd: e => {
          //onEnd是结束拖拽时触发，onUpdate是列表内元素顺序更新的时候触发，更多请看文末配置项
          //e.oldIndex为拖动一行原来的位置，e.newIndex为拖动后新的位置
          const targetRow = this.list.splice(e.oldIndex, 1)[0];
          this.list.splice(e.newIndex, 0, targetRow);
          let dragId = this.list[e.newIndex].recommendId; //拖动行的showNo
          let oneId, twoId;
          //拖动行的前一行
          if (this.list[e.newIndex - 1]) {
            oneId = this.list[e.newIndex - 1].recommendId;
          } else {
            oneId = "";
          }
          //拖动行的后一行
          if (this.list[e.newIndex + 1]) {
            twoId = this.list[e.newIndex + 1].recommendId;
          } else {
            twoId = "";
          }
          console.log("拖动行：" + dragId);
          console.log("前一行：" + oneId);
          console.log("后一行：" + twoId);
          //然后就可以Sortable发送请求了......
          // this.getList()
        }
      });
    },
    add() {
      checkShopLevel().then(response => {
        this.getAllList()
        this.dialogVisibleGoodsRecommend = true
      })


    },
    getAllList() {
      this.listLoading = true
      getGoodsList(this.listQueryAll).then(response => {
        this.allList = response.data.list
        this.totalAll = response.data.total
        this.listLoading = false
      })
    },
    getList() {
      this.listLoading = true
      this.listQuery.catePid = 0
      getGoodsRecommendList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleDelete() {
      const delVals = this.multipleSelection;
      if (!delVals || delVals.length <= 0) {
        this.$message({
          message: '请至少选择一条数据',
          type: 'error',
          duration: 2000
        })
        return;
      }
      this.$confirm('您确定要删除这些记录?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let values = [];
        delVals.forEach(val => {
          values.push(val.id);
        })
        batchDeleteGoodsRecommend(values.join(',')).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
        .catch(err => {
          console.error(err)
        })
    },
    confirmRecommendByTjb() {
      if (!this.selectBuyDayType) {
        this.$message({
          message: '请选择购买项目',
          type: 'error',
          duration: 2000
        })
        return;

      }
      console.log(this.selectBuyDayType)
      console.log(this.currentChooseGoods)
      let result = this.selectBuyDayTypeList.find((item) => {
        return item.id === this.selectBuyDayType
      })
      this.$confirm('您确认要花费[' + result.value + ']添加[' + result.label + ']的推荐商品吗?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let param = {
          'selectBuyDayType': this.selectBuyDayType,
          'chooseGoodsId': this.currentChooseGoods.id,
        }
        batchAddGoodsRecommendListByVirtualCurrency(param).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })

          this.dialogVisibleGoodsRecommendByVirtualCurrency = false
          this.selectBuyDayType = ""
        })
      })
        .catch(err => {
          console.error(err)
        })
    },
    addChooseGoods() {
      if (this.radio === 1) {
        //如果是直接添加
        const delVals = this.multipleSelection;
        if (!delVals || delVals.length <= 0) {
          this.$message({
            message: '请至少选择一条数据',
            type: 'error',
            duration: 2000
          })
          return;
        }
        this.$confirm('您确定要批量设置为推荐商品吗?', '提醒', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let values = [];
          delVals.forEach(val => {
            values.push(val.id);
          })
          batchAddGoodsRecommendList(values.join(',')).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '批量操作成功',
              type: 'success',
              duration: 2000
            })
          })
        })
          .catch(err => {
            console.error(err)
          })
      } else {

        if (this.currentChooseGoods == null) {
          this.$message({
            message: '请选择一条数据',
            type: 'error',
            duration: 2000
          })
          return;
        }
        //查看拥有的推荐币
        getInfoById().then(response => {
          let shop = response.data
          this.currentVirtualCurrency = shop.virtualCurrency
          this.selectBuyDayTypeList.forEach((item, index) => {
            if (item.num <= this.currentVirtualCurrency) {
              this.selectBuyDayTypeList[index].disabled = false
            } else {
              this.selectBuyDayTypeList[index].disabled = true
            }
          })
        })

        //如果是通过推荐币
        this.dialogVisibleGoodsRecommendByVirtualCurrency = true
      }
    },

    getGoodsQualityList(goodsId) {
      getGoodsQualityList(goodsId).then((result) => {
        this.goodsQualityList = result.data;
      })
    },
    handleViewGoodsQuality(row) {
      this.dialogFormVisible = true
      this.tempGoodsId = row.id
      this.goodsQuality = {}
      this.getGoodsQualityList(this.tempGoodsId)
    },
    handleDeleteGoodsQuality(id) {
      this.$confirm('您确定要删除这条记录?', '提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        deleteGoodsQuality(id).then(() => {
          this.getGoodsQualityList(this.tempGoodsId)
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
        .catch(err => {
          console.error(err)
        })
    },
    addGoodsQuality() {
      let formData = {
        goodsId: this.tempGoodsId,
        name: this.goodsQuality.name,
        value: this.goodsQuality.value,
        sort: this.goodsQuality.sort
      }

      addGoodsQuality(formData).then(() => {
        this.goodsQuality = {}
        this.getGoodsQualityList(this.tempGoodsId)
        this.$notify({
          title: '成功',
          message: '商品参数添加成功',
          type: 'success',
          duration: 2000
        })
      })
    },

  }
}
</script>

<style lang="scss" scoped>

.el-radio {
  margin-right: 0px !important;
}

.el-select-dropdown {
  span {
    white-space: pre !important;
  }
}

.el-select-dropdown__item {
  white-space: pre !important;
}

</style>
